// pages/map/map.js

import {request} from '../../request/index.js'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min");
var qqmapsdk;
import Notify from '../../vant/dist/notify/notify'
var util = require('../../utils/jingweiduzhuanhuan')  
// 地图标记点
// var markers = []
// 地图标记点的气泡
var callout = []
var markers = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: '', // 现在所处位置
    longitude: '', // 现在所处位置
    centerLat: '',
    centerLng: '',
    addressDetail:'', // 详细地址
    address: '', // 地图推荐显示地址
    typeStyle: '', // level的css显示
    show: false, // 显示隐患信息
    DgeForm: [], // 隐患信息
    NowAdress: '',
    ToUrl: '' ,//传隐患Id到details去
    id: '' ,//隐患Id
    deptId:'',
    // 划线
    // polyline:[{
    //   points:[],
    //   color:"#009199",
    //   width: 3,
    //   dottedLine: true
    // }],
    polyline: [],
    // 两点间距离 起点：from，终点： to
    from: '',
    to: '',
    distance: '',
    points: [], // 坐标点
    info: '', // 隐患信息
    ImgList: '', // 图片数组
  },
  ToChkList(){
    wx.navigateTo({
      url: '/pages/chkDate/chkDate',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(wx.getStorageSync('token'))
    // this.getInfos();
    qqmapsdk = new QQMapWX({
      key: 'TUHBZ-ZPFKU-XQAVA-BC4M4-ER4IZ-BXBLL'
    });
    this.getJingWeiDu();
    // console.log(wx.getStorageSync('deptId'))
    if (! wx.getStorageSync('deptId')){
      Notify({
       message: '还未加入部门，暂时无法查看隐患。\n 若有其他疑问，请联系管理员。',
       type: 'warning',
       duration: 6000});
      //  wx.getLocation({
      //   type: 'wgs84',
      //   success: (res)=> {
      //     // var latitude = res.latitude
      //     // var longitude = res.longitude
      //   }
      // })
   }
   else {
      this.getDgePos();
   }

     
    // wx.navigateTo({
    //   url: '/pages/my/my',
    // })
    //  this.getInfos();
  },
  regionchange(ev){
    console.log(ev)
  },

  // 计算两点间的距离
  calDistance(from,to){
    console.log(from)
    var _this = this;
    //调用距离计算接口
    qqmapsdk.calculateDistance({
        // from: from || '', //若起点有数据则采用起点坐标，若为空默认当前地址
        to: to, //终点坐标
        success: function(res) {//成功后的回调
          console.log(res);
          var res = res.result;
          // var dis = [];
          // for (var i = 0; i < res.elements.length; i++) {
          //   dis.push(res.elements[i].distance); //将返回数据存入dis数组，
          // }
          _this.setData({ //设置并更新distance数据
            distance: res.elements[0].distance
          });
          console.log(_this.data.distance)
        },
        fail: function(error) {
          console.error(error);
        },
        complete: function(res) {
          console.log(res);
        }
    });
  },


  //路线规划
   PlanRoad(from,to){
    var _this = this;
    console.log(from)
    //调用距离计算接口
    qqmapsdk.direction({
      mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      //from参数不填默认当前地址
      // from: from,
      to: to, 
      
      success: function (res) {
        console.log(res);
        var ret = res;
        var coors = ret.result.routes[0].polyline, pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        _this.setData({
          latitude:pl[0].latitude,
          longitude:pl[0].longitude,
          polyline: [{
            points: pl,
            color: '#FF0000DD',
            width: 4
          }]
        })
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
   }

  ,
// 计算中心点

getCenterPoint(){
  let that  = this
  var mapCtx = wx.createMapContext("map");
  // console.log(that.data.polyline[0].points)
  var a =  that.data.points
  console.log(a)
  mapCtx.includePoints({
        padding: [100],
        points: a,
        success: function (e){
          console.log(e,'2333')
          that.setData({
             polyline: [{
              points: a,
              color:"#009199",
              width: 3,
              dottedLine: true
          }],
          })
        },
        fail: function (e){
          console.log(e)
        }

      })
  
},

  /**
   * 获取经纬度
   */
getJingWeiDu() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        console.log(res);
        // wgs84->jcj02
        var a = that.data.points
        var str = res.latitude + ',' + res.longitude
        a.push({latitude: res.latitude ? res.latitude: null,longitude:  res.longitude ? res.longitude: null,})
        that.getCenterPoint();
        that.setData({
          longitude: res.longitude ? res.longitude: null,
          latitude: res.latitude ? res.latitude: null,
          centerLng: res.longitude ? res.longitude: null,
          centerLat: res.latitude ? res.latitude: null,
          points: a,
          from : str
        }
        // , () => {
          // that.jingWeiduToDiZhi(res.longitude,res.latitude)
        // }
        )
        // console.log(arr)
      }
    })
    
  },

// 经纬度转换成地址
  jingWeiduToDiZhi(latitude,longitude) {
    let that = this;
    // 调用接口
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude ? latitude : null,
        longitude: longitude ? longitude : null
      },
      // coord_type: 3, //baidu经纬度
      success: function(res){
        console.log(res);
        // let tempData = res.result.address_component;
        that.setData({
          addressDetail: res.result.address,
          address: res.result.formatted_addresses.recommend,
          NowAdress: res.result.formatted_addresses.recommend
        });
        that.ToGet()
      },
      fail: function(error) {
        console.log("err")
        console.error(error);
      },
      complete: function(res) {
        // console.log(res);
      }
    })
  },
  // 获取该供电局的隐患
  async getDgePos(){
    // console.log(wx.getStorageSync('deptId'))
      const res = await request({
      url: '/danger/findAll/',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
      success: function(res) {
        console.log(res)
      }
    })
    console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      var listData = res.data.data
      // console.log(listData)
      var arr = []
      for (var i=0;i<listData.length; ++i){
        if (listData[i].dgeStatus === 'done' ||  listData[i].dgeStatus === 'fail' || listData[i].dgeStatus === 'no'){
          continue;
        }
        var url = '';
        if (listData[i].dgeLevel === '一般'){
          url = '/img/2x/8smyb@2x.png'
        }
        else if(listData[i].dgeLevel === '严重'){
          url='/img/2x/8smse@2x.png'
        }
        else {
          url='/img/2x/8smimporant@2x.png'
        }
        var that = this;
        // 百度地图坐标转换成腾讯地图坐标
        var tengxun = util.transformFromBaiduToGCJ(listData[i].dgeLat,listData[i].dgeLng)
        console.log(tengxun)
       arr.push({
            latitude: tengxun.latitude,
            longitude: tengxun.longitude
        })
        markers = markers.concat({
          iconPath: url,
          id: listData[i].dgeId,
          callout:{
            content: listData[i].dgeName + '\n' + listData[i].dgeTypeName + '\n' ,
            fontsize: '42rpx',
            padding: '24rpx',
            color: '#009199',
            display: 'BYCLICK',
            textAlign: 'center',
            borderRadius: '16rpx',
            borderColor: '#009199',
            borderWidth: '4rpx'
          },
          // latitude: listData[i].dgeLat,
          // longitude: listData[i].dgeLng,
          latitude: tengxun.latitude,
          longitude: tengxun.longitude,
          width: '80rpx',
          height: '80rpx'
        })
        console.log(markers)
        console.log(arr)
        that.setData({
          markers: markers,
          // latitude: this.data.dgeLat,
          // longitude: this.data.dgeLng
        }) 
    }
    this.setData({
        points: arr
      })
      wx.getLocation({
        type: 'gcj02',
        success (res){
          console.log(res)
        }
    })
      console.log(that.data.points)
  }
  },
  upLoad:function(){
    wx.navigateTo({
      url: '/pages/uploaddge/uploaddge',
    })
  },
  SeeJw(e){
    console.log(e)
  },
  // 点击查看隐患窗口
  CheckDge(e){
    console.log(e.detail)
    if (e.detail.markerId){
      this.getDgeInfos(e.detail.markerId)
      this.setData({
        show: true,
        id: e.detail.markerId,
      })
    }
  },
  ToGet (){
    var address = this.data.addressDetail
    // var info = this.data.DgeForm["dgeInfo"] ? this.data.DgeForm["dgeInfo"] : '暂无描述'
    var fenlei = this.data.DgeForm["dgeTypeName"]
    var level = this.data.DgeForm["dgeLevel"]
    var name = this.data.DgeForm["dgeName"]
    var id = this.data.id
    this.setData({
      ToUrl: '/pages/details/details?Id='+ id + '&address=' + address + '&fenlei=' + fenlei + '&level=' + level + '&name=' + name
    })
  },
  // 弹窗隐患信息关闭
  onClose(){
    this.setData({
      show: false
    })
  },
  // 查询隐患信息来获取隐患分类
  async getDgeInfos(id){
    const res = await request({
      url: '/danger/findById/' + id,
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
    })
    // console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }else{
      var dgeInfo = res.data.data
      if (dgeInfo) {
          var infos = (dgeInfo.dgeInfo+ "").split('imgGroup:')[0]
            var info = (infos === 'null') ? '暂无隐患信息' : infos
            var imgstr = (dgeInfo.dgeInfo+ "").split('imgGroup:')[1]
            var arr = []
            if(imgstr) {
                arr = (imgstr+ "").split(",")
            }
            else {
                arr = ["null"]
            } 
          var type = dgeInfo.dgeLevel
          var classstyle = ''
          if (type == '一般' ) {
              classstyle = 'normal'
          } else if (type == '严重') {
            classstyle = 'serious'
          } else {
            classstyle = 'important'
          }
          this.setData({
            DgeForm: dgeInfo,
            typeStyle: classstyle,
            ImgList: arr,
            info: info
         })
         if (dgeInfo.dgeLng && dgeInfo.dgeLat){
          //  百度转腾讯
           var gcj = util.transformFromBaiduToGCJ(dgeInfo.dgeLat,dgeInfo.dgeLng)
           this.setData({
            centerLng: gcj.longitude,
            centerLat: gcj.latitude
           })
          //  this.jingWeiduToDiZhi(dgeInfo.dgeLat,dgeInfo.dgeLng)
           this.jingWeiduToDiZhi(gcj.latitude,gcj.longitude)
           var str = gcj.latitude + ',' + gcj.longitude
           this.calDistance(this.data.from,str)
           this.PlanRoad(this.data.from,str)
         }
      }
      this.ToGet()
      // console.log(this.data.DgeForm)
    }
  },
  goToAddress (){
    let that = this
    wx.showLoading({
      title: '正在寻找导航',
    })
    var result = util.transformFromBaiduToGCJ(that.data.DgeForm.dgeLat,that.data.DgeForm.dgeLng)
        wx.openLocation({
          latitude: result.latitude,
          longitude: result.longitude, 
          // scale: 8, // 缩放比例
          name: that.data.dgeName,
          address:that.data.address,
          success:function(r){
            wx.hideLoading({
              success: (res) => {},
            })
            console.log(r)
          }
        })
    // wx.getLocation({
    //   type:'gcj02', 
    //   success: function (res) {
    //     console.log(res.latitude); console.log(res.longitude);
    //     console.log(that.data.DgeForm)
        
    //   }
    // })
    
  },
  // 出发去巡检
  goToCheck:function(e){
    console.log(e);
    wx.showLoading({
      title: '正在前往巡视',
    })
    let that = this
    setTimeout(function(){
      wx.navigateTo({
        url: '/pages/sign/sign?dgeId='+ that.data.id,
      },wx.hideLoading({
        success: (res) => {},
      }))
    },5000)
    console.log(this.data.id)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if ( wx.getStorageSync('token')){
      this.checkToken()
    }
    else {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },
  async checkToken(){
    var token = wx.getStorageSync('token')
    if (token){
      const res = await request({
        url: '/user/verify',
        header:{
          'Authorization':'Bearer '+ token,
        },
        method: "get",
      })
      if (res.data.status !== 200){
         var title = res.data.msg ? res.data.msg :null
        if (title){
        wx.showToast({
          title: title,
          icon: 'none',
          duration: 2000
          })
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    } 
  }
},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
   wx.stopPullDownRefresh({
     success: (res) => {},
   })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})